package icasue.net.socket.thread;

import icasue.net.base.annotations.NotNull;
import icasue.net.socket.wareable.IdWorker;
import icasue.net.socket.wareable.SnowflakeId;
import icasue.net.socket.model.register.RegisterInfo;
import icasue.net.socket.utils.LogUtil;
import icasue.net.socket.utils.PoolUtil;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/3/18 下午4:56
 * @UpdateDate:
 * @Description: Acceptor 负责接收客户端的Socket请求，为每个Socket分配单独的线程资源,
 *                这里使用线程设计是为日后设计模式的变更，采用监视者模式 / Selector模式.
 */
public class Acceptor implements Runnable {

    private final ServerSocket serverSocket;
    private final IdWorker idWorker = new SnowflakeId(3, 1);
    private final Class<? extends RegisterInfo> regInfoClass;

    public Acceptor(@NotNull ServerSocket serverSocket,
                    @NotNull Class<? extends RegisterInfo> regInfoClass){
        this.serverSocket = serverSocket;
        this.regInfoClass = regInfoClass;
    }

    @Override
    public void run() {
        while (true){
            try {
                //Acceptor 线程接受来组客户端的连接请求
                Socket accept = serverSocket.accept();
                //创建游离态的SocketPoxyRunner.
                SocketProxy socketProxy = new SocketProxy(accept,idWorker.nextId(),regInfoClass);
                /*分配Socket线程 run.. */
                PoolUtil.submit(socketProxy);
            }catch (Throwable e){
                e.printStackTrace();
                LogUtil.error("Socket Server closed!");
            }
        }
    }
}
